#
#  Copyright (C) 2009 GSyC/LibreSoft
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
#    Author : Jose Antonio Santos Cadenas <jcaden __at__ gsyc __dot__ es>
#

from format.utils import generateResponse

PAGE = 0
N_ELEMS = 15

def error (format, message, code='500'):
    data = {'code'         : code,
            'description'  : message,}
    return generateResponse(format, data, "error")

def get_elements_per_page():
    return N_ELEMS

def get_num_pages(total_elems, elems_page):
    
    total_pages = total_elems / elems_page
    mod = total_elems % elems_page
    if mod != 0:
        total_pages = total_pages + 1
    
    return total_pages

def get_slice(request, list):
    if "page" in request.REQUEST:
        page = request.REQUEST["page"]
    else:
        page = None
    if "elems" in request.REQUEST:
        elems = request.REQUEST["elems"]
    else:
        elems = None
    try:
        page = int(page) - 1
        if page < 0:
            raise ValueError()
    except:
        page = PAGE
    try:
        elems = int(elems)
        if elems < 0:
            raise ValueError()
    except:
        elems=N_ELEMS
    f = elems * page
    t = f + elems
    
    return list[f:t], page+1, elems

def get_limits(request):
    if "page" in request.REQUEST:
        page = request.REQUEST["page"]
    else:
        page = None
    if "elems" in request.REQUEST:
        elems = request.REQUEST["elems"]
    else:
        elems = None
    try:
        page = int(page) - 1
        if page < 0:
            raise ValueError()
    except:
        page = PAGE
    try:
        elems = int(elems)
        if elems < 0:
            raise ValueError()
    except:
        elems=N_ELEMS
    f = elems * page
    t = f + elems
    return (f, t, page+1, elems)